<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="550px" @close="handleClose">
    <!-- 表单内容 -->
    <el-form :model="form" label-width="100px" v-if="currentOperation !== 'import'">
      <el-form-item label="类型" v-if="currentOperation === 'create' || currentOperation === 'edit'">
        <el-radio-group v-model="form.type">
          <el-radio value="folder">目录</el-radio>
          <el-radio value="file">文件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>
    </el-form>

    <!-- 图标方式选择文件类型并上传 -->
    <div v-else-if="currentOperation === 'import'" >
      <div class="version-choose">
        <el-radio-group v-model="form.versionStrategy" v-if="hasHistoryVersions">
          <el-radio label="new">新增版本</el-radio>
          <el-radio label="override">覆盖版本</el-radio>
        </el-radio-group>
        
        <el-select class="version-radio"  v-model="form.selectedVersionId" placeholder="请选择要覆盖的版本" v-if="form.versionStrategy === 'override' && historyVersions.length">
          <el-option v-for="version in historyVersions" :key="version.id" :label="version.versionDesc" :value="version.id"></el-option>
        </el-select>
        <el-input v-model="form.versionDesc" placeholder="请输入版本信息" :rules="[requiredVersion]"></el-input>
      </div>
      <div class="icon-upload">
        <div class="icon-grid">
          <div v-for="(type, index) in fileTypes" :key="type.value" class="icon-upload-item">
            <el-tooltip :content="type.label" placement="top">
              <el-upload
                :ref="(el) => setUploadRef(el, index)"
                :action="type.action"
                :before-upload="(file) => beforeUpload(file, type)"
                :on-change="(file, fileList) => handleFileChange(file, fileList, type)"
                :on-success="(response, uploadFile) => handleSuccess(uploadFile, type)"
                :on-error="handleError"
                :show-file-list="false"
                v-model:file-list="fileList"
                multiple
                :limit="1"  
                :auto-upload="false"
                :class="{'upload-icon': true}"
                :accept="getAccept(type)"
                :on-exceed="handleExceed"
              >
                <template #trigger>
                  <svg-icon width="45px" height="45px" :iconName="type.iconName" :iconColor="type.iconColor" />
                </template>
              </el-upload>
            </el-tooltip>
          </div>
        </div>
        <!-- 显示已选择文件列表 -->
        <el-table :data="fileList" style="width: 100%; margin-top: 16px;" v-if="fileList.length">
          <el-table-column prop="name" label="文件名"></el-table-column>
          <el-table-column label="大小">
            <template #default="scope">{{ formatFileSize(scope.row.size) }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="danger" @click="removeFile(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { getNodeHistory } from '@/api/repo/attachment'; // 假设API已经按照提供的结构定义
import { ElMessage } from 'element-plus';
import { computed, defineComponent, nextTick, onMounted, ref, watch } from 'vue';

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    operation: {
      type: String,
      required: true,
      validator: (value: string) => ['create', 'edit', 'import'].includes(value)
    },
    onSubmit: {
      type: Function,
      required: true
    },
    nodeData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible'],
  setup(props, { emit }) {
    const dialogVisible = ref(props.visible);
    const form = ref({
      type: 'folder',
      name: '',
      versionDesc: '',
      versionStrategy: 'new', // 新增或覆盖
      selectedVersionId: null // 当前选中的版本ID用于覆盖
    });
    const fileList = ref([] as any[]);
    const uploadRefs = ref([] as any[]);
    // 是否有历史版本
    const hasHistoryVersions = ref(false);
    const historyVersions = ref([]);
    const requiredVersion = (rule: any, value: string) => !!value || '版本信息是必填项';

    const fileTypes = [
      { value: 'word', label: 'Word (.doc, .docx)', iconName: 'word', iconColor: '#007bff', action: '#' },
      { value: 'excel', label: 'Excel (.xls, .xlsx, .csv)', iconName: 'excel', iconColor: '#28a745', action: '#' },
      { value: 'pdf', label: 'PDF (.pdf)', iconName: 'pdf', iconColor: '#dc3545', action: '#' },
      { value: 'ppt', label: 'PPT (.ppt)', iconName: 'ppt', iconColor: '#dc3545', action: '#' },
      { value: 'dwg', label: 'AutoCAD (.dwg)', iconName: 'dwg', iconColor: '#6c757d', action: '#' },
      { value: 'image', label: '图片 (.jpg, .png, .gif)', iconName: 'pic', iconColor: '#ffc107', action: '#' },
      { value: 'txt', label: '文本 (.txt)', iconName: 'txt', iconColor: '#17a2b8', action: '#' }, 
      { value: 'ofd', label: 'OFD (.ofd)', iconName: 'ofd', iconColor: '#f39c12', action: '#' }, 
      { value: 'video', label: '视频 (.mp4, .avi, .mkv)', iconName: 'video', iconColor: '#e65100', action: '#' }, 
    ];

    const currentOperation = computed(() => props.operation);

    const dialogTitle = computed(() => {
      switch (props.operation) {
        case 'create': return '新建节点';
        case 'edit': return '编辑节点';
        case 'import': return '导入文件';
        default: return '';
      }
    });

    const checkNodeVersions = async () => {
      if (props.nodeData?.id) {
        try {
          const data = await getNodeHistory({ nodeId: props.nodeData.id });
          historyVersions.value = data || [];
          hasHistoryVersions.value = historyVersions.value.length > 0;
        } catch (error) {
          console.error('Failed to fetch node versions:', error);
        }
      }
    };

    watch(() => props.visible, async (newValue) => {
      dialogVisible.value = newValue;
      if (!newValue) {
        resetForm();
      } else if (props.operation === 'edit' && props.nodeData) {
        loadNodeData();
      } else if (props.operation === 'import' && props.nodeData) {
        await checkNodeVersions();
      }
    });

    const handleClose = () => {
      emit('update:visible', false);
    };

    const handleSubmit = async () => {

      if (currentOperation.value !== 'import' && !form.value.name.trim()) {
        ElMessage.error('请输入名称');
        return;
      }

      let formData;
      try {
        if (currentOperation.value === 'import') {
          if (form.value.versionStrategy === 'override') {
            if(!form.value.selectedVersionId){
              ElMessage.error('请选择要覆盖的版本');
              return;
            }else{
              if (fileList.value.length === 0 && (!form.value.versionDesc.trim())) {
                ElMessage.error('导入文件和版本信息至少填写一个');
                return;
              }
            }
          
          }else{
            if (fileList.value.length === 0) {
              ElMessage.error('请选择至少一个文件进行导入');
              return;
            }

            // 验证版本信息是否已填写
            if (!form.value.versionDesc.trim()) {
              ElMessage.error('请输入版本信息');
              return;
            }
          }
          
          formData = {
            attachmentId: form.value.selectedVersionId,
            files: fileList.value.map(file => file.raw),
            versionDesc: form.value.versionDesc,
            versionStrategy: form.value.versionStrategy
          };
        } else {
          formData = { ...form.value };
        }

        await props.onSubmit(formData);
        handleClose();
        if (form.value.versionStrategy === 'override'){
          ElMessage.success(`编辑节点成功`);
        }else{
          ElMessage.success(`${dialogTitle.value}成功`);
        }
      } catch (error) {
        ElMessage.error(`操作失败：${error.message}`);
      }
    };

    const getAccept = (type: any): string => {
      const acceptMap = {
        word: '.doc,.docx',
        excel: '.xls,.xlsx,.csv',
        ppt: '.pptx,.ppt',
        pdf: '.pdf',
        dwg: '.dwg',
        image: '.jpg,.jpeg,.png,.gif',
        txt: '.txt',
        ofd: '.ofd',
        video: '.mp4,.avi,.mkv'
      };
      return acceptMap[type.value] || '';
    };

    const beforeUpload = (file: any, type: any): boolean | void => {
      const fileTypeMap = {
        word: ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
        excel: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'],
        pdf: ['application/pdf'],
        dwg: ['image/vnd.dwg'],
        image: ['image/jpeg', 'image/png', 'image/gif'],
        txt: ['text/plain'], 
        ofd: ['application/vnd.ofd+zip'], 
        video: ['video/mp4', 'video/x-msvideo', 'video/x-matroska'] 
      };
      const allowedTypes = fileTypeMap[type.value];
      const isValidType = allowedTypes.includes(file.type.toLowerCase());
      const isLt10M = file.size / 1024 / 1024 < 30;

      if (!isValidType) {
        ElMessage.error(`只能上传${type.label}!`);
        return false;
      }
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 30MB!');
        return false;
      }

      return true;
    };

    const handleFileChange = (file: any, newFileList: any[], type: any) => {
      if (file.status === 'ready') {
        const isValidType = beforeUpload(file.raw, type);
        if (isValidType !== false) {
          fileList.value.push({ ...file, type: type.value });
        }
      }
    };

    const handleExceed = (files: any[], fileList: any[]) => {
      ElMessage.warning(`当前限制选择最多1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    };

    const handleSuccess = (uploadFile: any, type: any) => {
      ElMessage.success('文件上传成功');
    };

    const handleError = () => {
      ElMessage.error('文件上传失败');
    };

    const removeFile = (index: number) => {
      const fileToRemove = fileList.value[index];
      fileList.value.splice(index, 1);

      nextTick(() => {
        const uploadIndex = fileToRemove.type ? fileTypes.findIndex(t => t.value === fileToRemove.type) : -1;
        if (uploadIndex >= 0 && uploadRefs.value[uploadIndex]) {
          uploadRefs.value[uploadIndex].clearFiles();
        }
      });
    };

    const resetForm = () => {
      form.value = {
        type: 'folder',
        name: '',
        versionDesc: '',
        versionStrategy: 'new',
        selectedVersionId: null
      };
      fileList.value = [];
    };

    const loadNodeData = () => {
      if (props.nodeData) {
        form.value.name = props.nodeData.label || '';
        form.value.type = props.nodeData.nodeType || 'folder',
        form.value.versionDesc = props.nodeData.versionDesc || '';
        fileList.value = props.nodeData.files || [];
      }
    };

    const formatFileSize = (size: number): string => {
      if (!size) return '';
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      let i = 0;
      while (size >= 1024 && ++i) {
        size /= 1024;
      }
      return `${(size + 0.0001).toFixed(2)} ${units[i]}`;
    };

    const setUploadRef = (el: any, index: number) => {
      if (el) {
        uploadRefs.value[index] = el;
      } else {
        uploadRefs.value[index] = null;
      }
    };

    onMounted(() => {
      fileTypes.forEach((_, index) => {
        if (!uploadRefs.value[index]) {
          uploadRefs.value[index] = null;
        }
      });
    });

    return {
      requiredVersion,
      dialogVisible,
      form,
      fileList,
      currentOperation,
      dialogTitle,
      handleClose,
      handleSubmit,
      getAccept,
      beforeUpload,
      handleFileChange,
      handleExceed,
      handleSuccess,
      handleError,
      removeFile,
      resetForm,
      loadNodeData,
      formatFileSize,
      setUploadRef,
      hasHistoryVersions,
      historyVersions,
      fileTypes,
    };
  }
});
</script>


<style scoped>

.version-radio{
  padding-bottom: 10px;
}

.icon-upload {
  display: flex;
  flex-wrap: wrap; 
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr); /* 每行最多6个图标 */
  gap: 16px; /* 图标之间的间距 */
}

.icon-upload-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  padding: 12px;
  font-size: 24px;
  cursor: pointer; /* 显示指针样式 */
}

.version-choose .el-input ::v-deep(.el-input__inner) {
  border-color: red;
}

.version-choose .el-input ::v-deep(.el-input__placeholder)::after {
  content: '*';
  color: red;
}

</style>